package cn.com.hhrcw.utils;

import cn.com.hhrcw.constant.CommonConstant;
import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.login.AbstractLogin;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.SpringContextUtils;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author lixingxing
 */
@Slf4j
public class SubjectUtils {

    private SubjectUtils() {
    }

    /**
     * 暂时先改为10分钟
     */
    public static final int EXPIR_DAY = 30;

    /**
     * 用户登陆
     *
     * @param loginAbstract
     */
    public static void login(AbstractLogin loginAbstract) {
        SpringContextUtils.getApplicationContext().getAutowireCapableBeanFactory().autowireBean(loginAbstract);
        Object user = loginAbstract.login();
        Assert.notNull(user, "登陆失败");
        RedisTemplate redisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class);
        SysUser member = (SysUser) user;
        String sign = JwtUtil.sign(member.getUsername(), member.getPassword(), Dict.create().set("platform", "0"));

        //hl 添加
        redisTemplate.opsForValue().set(CommonConstant.PREFIX_USER_TOKEN + sign, user, EXPIR_DAY, TimeUnit.MINUTES);

        // 金法添加签名 为了个人端可以上传
        redisTemplate.opsForValue().set(CommonConstant.PREFIX_USER_PERSONAL_TOKEN + sign, sign, EXPIR_DAY, TimeUnit.MINUTES);
        loginAbstract.setToken(sign);
        loginAbstract.success(user);
    }

    /**
     * 获取当前登陆用户
     */
    public static Object getSubject() {
        String token = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TOKEN);
        RedisTemplate redisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class);
        return redisTemplate.opsForValue().get(CommonConstant.PREFIX_USER_TOKEN + token);
    }

    /**
     * 退出登陆
     */
    public static void logout() {
        String token = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TOKEN);
        RedisTemplate redisTemplate = SpringContextUtils.getBean("redisTemplate", RedisTemplate.class);
        redisTemplate.delete(CommonConstant.PREFIX_USER_TOKEN + token);
    }
}
